﻿using Artizan.Iot.Hub.Mqtt.AspNetCore.Servser;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using MQTTnet.AspNetCore;
using MQTTnet.Server;


namespace Artizan.Iot.Hub.Mqtt.AspNetCore.Extensions
{
    public static class IotHubMqttServerExtensions
    {
        /// <summary>
        /// MQTTnet 集成 AspNetCore：
        ///    https://github.com/dotnet/MQTTnet/wiki/Server#validating-mqtt-clients
        /// </summary>
        public static void AddIotHubMqttServer(this IServiceCollection services,
            Action<AspNetMqttServerOptionsBuilder> configure)
        {
            services.AddHostedMqttServerWithServices(builder =>
            {
                configure(builder);
            });
            services.AddMqttConnectionHandler();
            services.AddConnections();
            services.AddMqttTcpServerAdapter();
            services.AddMqttWebSocketServerAdapter();
        }

        public static void UseIotHubMqttServer(this IApplicationBuilder app, Action<MqttServer>? configure)
        {
            app.UseMqttServer(mqttServer =>
            {
                app.ApplicationServices.GetRequiredService<IIotHubMqttServer>()
                  .ConfigureMqttServer(mqttServer);

                if (configure != null)
                {
                    configure(mqttServer);
                }
            });
        }
    }
}
